// pages/ucenter/drvlicense/drvlicense.js
const util = require('../../../utils/util')
const FormValidation = require('../../../utils/formValidation')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    limitSize: 2, //上传图片大小限制 单位M
    apiImgUrl: app.globalData.apiImgUrl,
    //处理类型
    carTypeArray: [{
        value: '02',
        text: "小型汽车"
      },
      {
        value: '01',
        text: "大型汽车"
      },
      {
        value: '03',
        text: "使馆汽车"
      },
      {
        value: '04',
        text: "领馆汽车"
      },
      {
        value: '05',
        text: "境外汽车"
      },
      {
        value: '06',
        text: "外籍汽车"
      },
      {
        value: '07',
        text: "普通摩托车"
      },
      {
        value: '08',
        text: "轻便摩托车"
      },
      {
        value: '09',
        text: "使馆摩托车"
      },
      {
        value: '10',
        text: "领馆摩托车"
      },
      {
        value: '11',
        text: "境外摩托车"
      },
      {
        value: '12',
        text: "外籍摩托车"
      },
      {
        value: '13',
        text: "低速车"
      },
      {
        value: '14',
        text: "拖拉机"
      },
      {
        value: '15',
        text: "挂车"
      },
      {
        value: '16',
        text: "教练汽车"
      },
      {
        value: '17',
        text: "教练摩托车"
      },
      {
        value: '18',
        text: "试验汽车"
      },
      {
        value: '19',
        text: "试验摩托车"
      },
      {
        value: '20',
        text: "临时入境汽车"
      },
      {
        value: '21',
        text: "临时入境摩托车"
      },
      {
        value: '22',
        text: "临时行驶车"
      },
      {
        value: '23',
        text: "警用汽车"
      },
      {
        value: '24',
        text: "警用摩托"
      },
      {
        value: '25',
        text: "原农机号牌"
      },
      {
        value: '26',
        text: "香港入出境车"
      },
      {
        value: '27',
        text: "澳门入出境车"
      },
      {
        value: '51',
        text: "大型新能源汽车"
      },
      {
        value: '52',
        text: "小型新能源汽车"
      }
    ],
    carTypeIndex: 0, //车辆类型索引
    carType: '小型汽车', //车辆类型名称
    carTypeId: 2, //车辆类型值

    provinceShort: '京', //省份简称
    isShowProvinceSelect: false, //是否显示省份选择组件
    carID: null, //车款id
    carName: '请选择车款', //车款名称
    carNameList: [], //车款列表
    scrollLeft: 0, //左滑

    //车型组件
    carBrandModel: '请选择车型', //车型选择
    carBrand: '', //品牌
    carBrandId: '', //品牌id
    carModel: '', //车型
    carModelId: '', //车型id

    isScen: false, //是否是已经有扫描过的信息

    Address: '', //住址
    EngineNo: '', //发动机号
    IssueDate: '请选择发证日期', //发证日期
    Model: '', //品牌型号
    Owner: '', //所有人
    PlateNo: '',
    RegisterDate: '请选择注册日期', //注册日期
    UseCharacter: '', //使用性质
    VehicleType: '', //车辆类型
    VIN: '', //车辆识别代号
    registrStratDate: '2010-01-01',
    registrEndDate: util.formatDate(new Date(), 'yyyy-MM-dd'),

    issueStratDate: '2010-01-01',
    issueEndDate: util.formatDate(new Date(), 'yyyy-MM-dd'),

    exampleTile: '',
    exampleImgUrl: '',
    exampleConfirmBtnText: '确定',
    isHiddenExample: true,
    exampleSubTitle: '',
    exampleText: '',
    isShowCamera: false, //是否显示摄像头
    isShowCameraBg: false, //摄像头遮罩
    cameraHeight: null, //照相机的高度
    cameraTop: null, //相机组件距离顶部的距离
    isAuthority: false, //是否授权了摄像头权限
    ctx: null, //全局的摄像头对象
    cameraImgHeight: null, //摄像头遮罩的高度
    cameraMaskHeight: null, //底部遮罩高度
    isShowCameraMask: false, //是否显示底部遮罩
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this;
    //设置验证
    self.initValidate();

    wx.getSystemInfo({
      success(res) {
        let height = Math.floor(res.windowWidth * 1100 / 750);
        let maskHeight = Math.ceil(res.windowHeight - height);
        self.setData({
          cameraImgHeight: height,
          cameraMaskHeight: maskHeight - app.globalData.CustomBar,
          cameraTop: app.globalData.CustomBar
        })
      }
    });


    //初始化页面时提前获取权限
    // wx.authorize({
    //   scope: 'scope.camera',
    //   success() {
    //     // 用户已经同意小程序使用摄像头功能
    //     const ctx = wx.createCameraContext();
    //     self.setData({
    //       ctx: ctx
    //     });
    //   },
    //   fail() {

    //   }
    // })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //获取车款信息
  getCarName: function (e) {
    let self = this;
    let url = app.globalData.apiRootUrl + '/Car/GetCarListBySeriesId';
    if (self.data.carModelId == "") {
      wx.showToast({
        title: '您选择的车型没有车款信息',
        icon: 'none'
      })
      return;
    }
    app.httpRequest({
      url: url,
      showLoading: true,
      data: {
        SerialId: self.data.carModelId
      },
      success: function (res) {
        let rdata = res.data;
        //console.log(res);
        if (rdata.status == 0 && rdata.data) {
          self.setData({
            carNameList: rdata.data,
            modalName: e.currentTarget.dataset.target
          })
        } else {
          wx.showToast({
            title: '车款信息获取失败',
            icon: 'none'
          })
        }
      }
    });
  },
  //车款点击选择
  selectSeriesTap: function (e) {
    let self = this;
    console.log(e);
    let carID = e.currentTarget.dataset.carid;
    let carName = e.currentTarget.dataset.carname;
    self.setData({
      carID: carID, //车款id
      carName: carName, //车款名称
      modalName: null
    });
  },
  /**
   * 车牌大写
   */
  plateNoInput(e) {
    let v = e.detail.value;
    this.setData({
      PlateNo: v.toUpperCase()
    });
  },
  /**
   * 车牌失去焦点
   */
  plateNuBlur() {
    let self = this;
    if (util.isNullOrEmpty(self.data.carModel)) {
      if (/^[A-Z]{1}[A-Z0-9]{5,6}$/.test(self.data.PlateNo)) {
        let tmp = self.data.provinceShort + self.data.PlateNo;
        self.getCarModel(tmp);
      }
    }

  },
  //车辆类型选择
  carTypePickerChange: function (e) {
    let self = this;
    let carTypeArray = self.data.carTypeArray;
    self.setData({
      carTypeIndex: e.detail.value,
      carType: carTypeArray[e.detail.value].text,
      carTypeId: carTypeArray[e.detail.value].value
    })
  },
  //显示省份简称
  showProCode: function () {
    this.setData({
      isShowProvinceSelect: true
    });
  },
  //关闭省份选择
  onCacnelClick: function () {
    this.setData({
      isShowProvinceSelect: false
    });
  },
  //省份选择
  onSureClick: function (e) {
    this.setData({
      provinceShort: e.detail.proValue,
      isShowProvinceSelect: false
    })
  },
  //前往车型选择页面
  goToChoiceCarModelTap: function () {
    wx.navigateTo({
      url: '/pages/carmake/carmake?showLevel=2',
    })
  },
  /**
   * 拍照识别
   */
  vehicleTap: function () {
    let self = this;
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择上传'],
      success(res) {
        if (res.tapIndex == 0) { //用户选择拍照          
          // self.checkCamera();  //如果能走到这里就不用再次检测权限了
          self.setData({
            isShowCamera: true //是否显示摄像头
          })
          setTimeout(function () {
            self.setData({
              isShowCameraBg: true //摄像头遮罩
            })
          }, 2000)
        } else if (res.tapIndex == 1) { //用户选择从相册中找         
          self.chooseImage();
        }
      },
      fail(res) {
        //console.log(res.errMsg)
      }
    })
  },
  /**
   * 检测是否有摄像头权限
   */
  checkCamera: function () {
    let self = this;
    util.checkSetting("scope.camera").then(function (res) {
      // console.log(res);
      const ctx = wx.createCameraContext();
      self.setData({
        ctx: ctx
      });
      self.setData({
        exampleTile: '',
        exampleImgUrl: 'example/xsz.jpg',
        exampleSubTitle: '行驶证识别声明',
        exampleText: '请对准行驶证正面拍照上传，拍照时确保图像清晰，避免反光影响，以提高识别的正确率。',
        exampleConfirmBtnText: '马上上传',
        isHiddenExample: false
      });
    }, function (res) {
      console.log(res)
      //没有权限，则开启设置页面
      util.openSetting("scope.camera", "需要获取摄像头权限?").then(function (rt) {
        const ctx = wx.createCameraContext();
        self.setData({
          ctx: ctx,
          isAuthority: true
        });
      }, function (rt) {

      });
    });
  },
  /**
   * 相册选择
   */
  chooseImage: function () {
    let self = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        if (tempFilePaths) {
          //单位KB
          let sizeKb = res.tempFilePaths.size / 1024;
          //单位KB
          let limitSize = self.data.limitSize * 1024;

          if (sizeKb > limitSize) {
            wx.showToast({
              title: '上传图片大小不能超过2M',
              icon: 'none'
            });
          } else {
            wx.showLoading({
              title: '图片识别中...'
            })
            self.upImgFile(res.tempFilePaths);
          }
        }
      }
    })
  },
  //模拟拍照
  takePhoto: function () {
    let self = this;
    self.data.ctx.takePhoto({
      quality: 'normal',
      success: (res) => {
        console.log(res);
        let resPath = [res.tempImagePath];
        self.setData({
          isShowCamera: false,
          isShowCameraBg: false
        })
        wx.getFileInfo({
          filePath: res.tempImagePath,
          success(res) {
            //单位KB
            let sizeKb = res.size / 1024;
            //单位KB
            let limitSize = self.data.limitSize * 1024;

            if (sizeKb > limitSize) {
              wx.showToast({
                title: '上传图片大小不能超过2M',
                icon: 'none'
              })
            } else {
              wx.showLoading({
                title: '图片识别中...'
              })
              self.upImgFile(resPath);
            }
          }
        })
      }
    })
  },
  //图片上传
  upImgFile: function (tempFilePaths) {
    let self = this;
    wx.uploadFile({
      url: app.globalData.apiRootUrl + '/WxMini/VehicleLicenseOcr',
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {},
      success: function (res) {
        console.log(res);
        let rdata = JSON.parse(res.data);
        if (rdata.status == 0 && rdata.data) {
          wx.hideLoading();
          self.setData({
            Address: rdata.data.addr, //住址
            EngineNo: rdata.data.engine_num, //发动机号
            IssueDate: rdata.data.issue_date, //发证日期
            Model: rdata.data.model, //品牌型号
            Owner: rdata.data.owner, //所有人
            provinceShort: rdata.data.plate_num.substring(0, 1),
            PlateNo: rdata.data.plate_num.substring(1),
            RegisterDate: rdata.data.register_date, //注册日期
            UseCharacter: rdata.data.use_character, //使用性质
            VehicleType: rdata.data.vehicle_type, //车辆类型
            VIN: rdata.data.vin, //车辆识别代号
            isScen: true
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: rdata.message,
            icon: 'none'
          })
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '上传图片失败',
          icon: 'none'
        })
      }
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  /**
   * 关闭拍照
   */
  closeCameraTap() {
    let self = this;
    self.setData({
      isShowCamera: false, //是否显示摄像头
      isShowCameraBg: false //摄像头遮罩
    })
  },
  /**
   * 表单提交
   */
  formSubmit: function (res) {
    let self = this;
    const data = res.detail.value;
    // 传入表单数据，调用验证方法
    if (!this.FrmValidate.checkForm(data)) {
      const error = this.FrmValidate.errorList[0];
      wx.showToast({
        title: error.msg,
        icon: 'none'
      })
      return false
    }

    //车牌号码
    data.PlateNo = self.data.provinceShort + data.PlateNo;
    data.UserID = app.globalData.userInfo.UserID;
    data.Brand = self.data.carBrand;
    data.ModelID = self.data.carModelId;
    data.Model = self.data.carModel;
    data.CarID = self.data.carID;
    data.CarName = self.data.carName;

    self.submitForm(data);
  },
  /**
   * 提交表单
   */
  submitForm(data) {
    let self = this;
    let url = app.globalData.apiRootUrl + '/User/SaveVehicleLicense';
    app.httpRequest({
      url: url,
      showLoading: true,
      method: "POST",
      data: data,
      success: function (res) {
        let rdata = res.data;
        //console.log(res);
        if (rdata.status == 0) {
          app.globalData.userInfo.VehicleStatus = rdata.data.VehicleStatus;
          app.globalData.userInfo.CarGroupIds.push(rdata.data.CarGroupID);
          if (app.globalData.userInfo.CardLevel == 0) {
            app.globalData.userInfo.CardLevel = 1;
          }
          // app.globalData.userInfo.PlateNo = rdata.data.PlateNo || '';
          // app.globalData.userInfo.ModelName = rdata.data.Brand + ' ' + rdata.data.Model;
          app.setUserInfo(app.globalData.userInfo);

          if (app.globalData.userInfo.CardLevel == 2) { //判断如果是黑金卡，则直接跳转到我的页面
            wx.reLaunch({
              url: '/pages/ucenter/index/index',
            })
          } else {
            wx.switchTab({
              url: '/pages/vipCard/vipCard',
            })
          }


        } else {
          wx.showToast({
            title: '手机号绑定失败，请重新验证',
            icon: 'none'
          });
        }
      }
    });
  },
  /**
   * 验证初始化
   */
  initValidate() {
    // 验证字段的规则
    const rules = {
      PlateNo: {
        required: true,
        plateno: true
      },
      Owner: {
        required: true
      },
      EngineNo: {
        required: true
      },
      BrandID: {
        required: true
      },
      CarID: {
        required: true
      }
    };

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      Owner: {
        required: '请输入车辆所有人'
      },
      PlateNo: {
        required: '请输入车牌号码',
        plateno: '请输入正确的车牌号码'
      },
      EngineNo: {
        required: '请输入发动机号'
      },
      BrandID: {
        required: '请选择车型'
      },
      CarID: {
        required: '请选择车款'
      }
    };
    // 创建实例对象
    this.FrmValidate = new FormValidation(rules, messages)
  },
  /**
   * 根据车牌获取车型
   */
  getCarModel(plateNo) {
    let self = this;
    let url = app.globalData.apiRootUrl + '/InsureALL/GetInsureAllByPlateNo';
    app.httpRequest({
      url: url,
      method: "GET",
      data: {
        PlateNo: plateNo,
        UserId: app.globalData.userInfo.UserID
      },
      success: function (res) {
        let rdata = res.data;
        //console.log(res);
        if (rdata.status == 0) {

          self.setData({
            //车型组件
            carBrandModel: rdata.data.CarBrand + ' ' + rdata.data.CarSerial, //车型选择
            carBrand: rdata.data.CarBrand, //品牌
            carBrandId: rdata.data.CarBrandID, //品牌id
            carModel: rdata.data.CarSerial, //车型
            carModelId: rdata.data.CarSerialID, //车型id
            EngineNo: rdata.data.EngineNo
          })

        }
      }
    });
  },

  /**
   * 注册日期
   */
  registrDateChange(e) {
    this.setData({
      RegisterDate: e.detail.value
    })
  },
  /**
   * 发证日期
   */
  issueDateChange(e) {
    this.setData({
      issueDate: e.detail.value
    })
  },
  //示例图片关闭按钮
  exampleCloseTap: function () {
    let self = this;
    self.setData({
      isHiddenExample: true
    })
  },
  //示例图片确定按钮
  exampleConfirmTap: function () {
    let self = this;
    self.setData({
      isHiddenExample: true
    })
    if (self.data.exampleSubTitle) { //如果副标题有值，那就是拍照
      self.vehicleTap();
      self.setData({
        isHiddenExample: true
      })
    }
  },
  //示例图片显示
  showExampleTap: function (e) {
    let self = this;
    let type = e.currentTarget.dataset.imgtype;
    switch (type) {
      case 'engineno':
        self.setData({
          exampleTile: '发动机号码',
          exampleImgUrl: 'example/sl-engine-no.jpg',
          exampleSubTitle: '',
          exampleText: '',
          exampleConfirmBtnText: '确定',
          isHiddenExample: false
        });
        break;
      case 'vin':
        self.setData({
          exampleTile: '车架号',
          exampleImgUrl: 'example/sl-VIN.jpg',
          exampleSubTitle: '',
          exampleText: '',
          exampleConfirmBtnText: '确定',
          isHiddenExample: false
        });
        break;
      case 'scan':
        self.checkCamera();
        break;
    }
  },
})